//
//  MovieDetailVC.m
//  One
//
//  Created by mac on 16/5/28.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MovieDetailVC.h"
#import "MovieDetailCell.h"
#import "Util.h"
#import <AVFoundation/AVFoundation.h>
#import "TicketViewController.h"
#import "PlayerVC.h"
#import "ScoreVC.h"

@interface MovieDetailVC ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *myTable;
    NSMutableArray *commentArr;
    MovieDetailObject *detaiObj;
    MovieStroyObject *storyObj;
    int titleH;
    int contentH;
    AVPlayer *player;
    AVPlayerItem *playerItem;
    TicketViewController *ticketVC;
    NSString * htmlStr;
    PlayerVC *playerView;
    ScoreVC *scoreView;
    
}
@end

@implementation MovieDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //[self GetData];
    [self layoutTable];

}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self GetData];
}
- (void)layoutTable
{
    [self getHeight];
    myTable = [[UITableView alloc ] initWithFrame:CGRectMake(0, -44, WIDTH, HEIGHT + 64 ) style:UITableViewStyleGrouped];
    myTable.dataSource = self;
    myTable.delegate = self;
    [self.view addSubview:myTable];
    
}

#pragma mark --getData
- (void)GetData
{
    NSLog(@"-------%@",self.topicObj.ID);
    NSDictionary *comPara = @{URLKEY : [NSString stringWithFormat: @"comment/praiseandtime/movie/%@/0",self.topicObj.ID ]};
    [HttpManager requestDataWithParameters:comPara requestMethod:@"GET" completionBlock:^(NSDictionary *responseDic) {
        NSArray *arr = responseDic[@"data"][@"data"] ;
        commentArr = [[NSMutableArray alloc] init];
        [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MovieComment *comObj = [MovieComment mj_objectWithKeyValues:obj];
            [commentArr addObject:comObj];
            NSLog(@"%@",commentArr);
            [myTable reloadData];
        }];
    }];
    
    
    
    NSDictionary *detailPara = @{URLKEY : [NSString stringWithFormat: @"movie/detail/%@",self.topicObj.ID]};
    [HttpManager requestDataWithParameters:detailPara requestMethod:@"GET" completionBlock:^(NSDictionary *responseDic) {
        NSDictionary *dic = responseDic[@"data"];
        detaiObj = [MovieDetailObject mj_objectWithKeyValues:dic];
        NSLog(@"%@",detaiObj.title);
        [myTable reloadData];
    }];
    
    NSLog(@"%@",self.topicObj.ID);
    NSDictionary *storyDic = @{URLKEY : [NSString stringWithFormat:@"movie/%@/story/1/0",self.topicObj.ID]};
    
    [HttpManager requestDataWithParameters:storyDic requestMethod:@"GET" completionBlock:^(NSDictionary *responseDic) {
        NSArray *arr = responseDic [@"data"][@"data"];
        NSDictionary *dic = arr[0];
        storyObj = [MovieStroyObject mj_objectWithKeyValues:dic];
        NSLog(@"%@",storyObj.title);
        [myTable reloadData];
    }];
    
    
//    NSDictionary *ticketPara = @{URLKEY : [NSString stringWithFormat:@"movie/buyticket/%@?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0NjM5Mjk2MTgsInVzZXJpZCI6IjY4MDczMDUifQ.F5v0dNsB2b0M8kl91TYtOP1WwdEkZ2DTllnUTbgchkM",self.topicObj.ID]};
//    [HttpManager requestDataWithParameters:ticketPara requestMethod:@"GET" completionBlock:^(NSDictionary *responseDic) {
//        htmlStr = (NSString *)responseDic;
//    
//        NSLog(@"ticket----%@",htmlStr);
//    }];
    
}

#pragma mark--TableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return 1;
    }else
    {
        return commentArr.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    int  h ;
    switch (section) {
        case 0:
        {
            h= 0;
        }
            break;
        case 1:
        {
            h= 40;
        }
            break;
        case 2:
        {
            h= HEIGHT/3;
        }
            break;
        default:
            break;
    }
    return h;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionView = nil;
    if (section == 0) {
        sectionView = nil;
    }else if (section ==1)
    {
        sectionView =[self creatViewInSection:1 WithView:sectionView];
    }else
    {
        sectionView = [self creatViewInSection:2 WithView:sectionView];
    }
    return sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *cellArr = [[NSBundle mainBundle]loadNibNamed:@"MovieDetailCell" owner:nil options:nil];
    MovieDetailCell *cell = nil;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        cell = cellArr[0];
        
        [cell.deepview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(WIDTH, HEIGHT/3-50));
        }];
        
        [cell.bgButton sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",detaiObj.detailcover]] forState:UIControlStateNormal];
        cell.bgButton.clipsToBounds = YES;
        
        [self BeGanAnimateWithButton:cell.bgButton];
        cell.bgButton.tag = 10000;
        [cell.bgButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        if (self.topicObj.score != nil) {
            cell.scoreLabel.text = [NSString stringWithFormat:@"%@",self.topicObj.score];
            cell.lineImgView.image = [UIImage imageNamed:@"redline_81x5_"];
            cell.showTimeLabel.text = nil;
        }else
        {
            cell.scoreLabel.text = nil;
            cell.lineImgView.image = nil;
            cell.showTimeLabel.text = @"即将上映";
        }
        cell.ticketBtn.tag = 3333;
        cell.scoreBtn.tag = 3334;
        [cell.ticketBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.scoreBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }else if (indexPath.section == 1){
        cell = cellArr[1];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.headBtn sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",storyObj.web_url]] forState:UIControlStateNormal];
        cell.nameLabel.text = [NSString stringWithFormat:@"%@",storyObj.user_name];
        cell.timeLabel.text = [NSString stringWithFormat:@"%@",storyObj.input_date];
        cell.storyNameLabel.text = [NSString stringWithFormat:@"%@",storyObj.title];
        cell.stroryTextLabel.text = [NSString stringWithFormat:@"%@",storyObj.content];
        NSLog(@"price---%@",storyObj.praisenum);
        [cell.priceNumBtn setTitle:[NSString stringWithFormat:@"%@",storyObj.praisenum] forState:UIControlStateNormal];
        [cell.priceNumBtn setImage:[UIImage imageNamed:@"like_selected_44x44_"] forState:UIControlStateSelected];
        [cell.priceNumBtn setImage:[UIImage imageNamed:@"like_default_44x44_"] forState:UIControlStateNormal];
        cell.priceNumBtn.selected = NO;
        
        cell.priceNumBtn.tag = 666;
        [cell.priceNumBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [cell.stroryTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(contentH + 1300);
        }];
        [cell.storyNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(titleH);
        }];
    }else{
        cell = cellArr[2];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        MovieComment *commObj = commentArr[indexPath.row];
        [cell.comHeadBtn sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",commObj.web_url]]  forState:UIControlStateNormal];
        cell.comNameLable.text = [NSString stringWithFormat:@"%@",commObj.user_name];
        cell.comTimeLabel.text = [NSString stringWithFormat:@"%@",commObj.input_date];
        NSLog(@"comScro--%@",commObj.score);
        cell.comScoreLabel.text = [NSString stringWithFormat:@"%@",commObj.score];
        [cell.comPriceBtn setTitle:[NSString stringWithFormat:@"%@",commObj.praisenum] forState:UIControlStateNormal];
        [cell.comPriceBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.comPriceBtn.tag = indexPath.row + 10;
        cell.ComTextLabel.text = [NSString stringWithFormat:@"%@",commObj.content];
        int height = [Util getTextHeightWithText:commObj.content withSize:CGSizeMake(WIDTH - 60, MAXFLOAT) font:Font(15)];
        [cell.ComTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(height + 100);
        }];
        
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int  height;
    if (indexPath.section == 0) {
        height = HEIGHT/3;
    }else if(indexPath.section == 1)
    {
        height = 40 + titleH + contentH + 1300;
    }else
    {
        MovieComment *obj = commentArr[indexPath.row];
        int add = [Util getTextHeightWithText:obj.content withSize:CGSizeMake(WIDTH - 60 , MAXFLOAT) font:Font(15)];
        height = 50 + add + 60 ;
    }
    return height;
}

#pragma mark--util

- (void)getHeight
{
    titleH = [Util getTextHeightWithText:storyObj.title withSize:CGSizeMake(WIDTH-81, MAXFLOAT) font:Font(16)];
    contentH = [Util getTextHeightWithText:storyObj.content withSize:CGSizeMake(WIDTH-81, MAXFLOAT) font:Font(15)];
}

- (UIView *)creatViewInSection:(int)section WithView:(UIView *)view
{
    if (section == 1) {
        view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
        view.backgroundColor = [UIColor colorWithWhite:0.949 alpha:1.000];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 100, 20)];
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor colorWithRed:0.187 green:0.173 blue:0.188 alpha:1.000];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"电影故事";
        [view addSubview:label];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [view addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(15);
            make.height.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(44, 44));
        }];
        [button setBackgroundImage:[UIImage imageNamed:@"unofficial_plot_highlighted_19x19_"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"unofficial_plot_highlighted_19x19_"] forState:UIControlStateSelected];
        
        
    }else{
        view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/3)];
        view.backgroundColor = [UIColor colorWithWhite:0.949 alpha:1.000];
        view.tag = 10086;
        
        UILabel *label  = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 100, 30)];
        label.font = [UIFont systemFontOfSize:12];
        label.text = @"一个 电影表";
        label.tag = 123456;
        label.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label];
        for (int i = 0; i < 3; i ++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(((HEIGHT / 2)-100)+(5+44)*i, 0, 44, 44);
            button.tag = i + 100;
            [button addTarget: self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [view addSubview:button];
        }
        UIButton *button1 = (UIButton *)[view viewWithTag:100];
        [button1 setBackgroundImage:[UIImage imageNamed:@"plot_default_44x45_"] forState:UIControlStateNormal];
        [button1 setBackgroundImage:[UIImage imageNamed:@"plot_selected_44x45_"] forState:UIControlStateSelected];
        button1.selected = YES;
        
        
        UIButton *button2 = (UIButton *)[view viewWithTag:101];
        [button2 setBackgroundImage:[UIImage imageNamed:@"still_default_44x45_"] forState:UIControlStateNormal];
        [button2 setBackgroundImage:[UIImage imageNamed:@"still_selected_44x45_"] forState:UIControlStateSelected];
        
        UIButton *button3 = (UIButton *)[view viewWithTag:102];
        [button3 setBackgroundImage:[UIImage imageNamed:@"actor_default_44x45_"] forState:UIControlStateNormal];
        [button3 setBackgroundImage:[UIImage imageNamed:@"actor_selected_44x45_"] forState:UIControlStateSelected];
        
        for ( int i = 0; i < 3; i ++) {
            UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, WIDTH, HEIGHT/3-80)];
            btnView.backgroundColor = [UIColor whiteColor];
            btnView.tag = 200 + i;
            [view addSubview:btnView];
        }
        
        UIView *defauView = (UIView *)[view viewWithTag:200];
        UIImageView *bgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, defauView.frame.size.height)];
        bgview.image = [UIImage imageNamed:@"GrossBorder_414x126_"];
        [defauView addSubview:bgview];
        [view bringSubviewToFront:defauView];
        
        
        NSString *str = detaiObj.keywords;
        NSArray *keyArr = [str componentsSeparatedByString:@";"];
        NSLog(@"arr---%@",keyArr);
        for (int i = 0; i < 3; i ++) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH/3) * i, 0, WIDTH/3, (HEIGHT / 3 - 80)/2)];
            label.text = keyArr[i];
            label.font = [UIFont systemFontOfSize:14];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor colorWithRed:0.498 green:0.647 blue:0.894 alpha:1.000];
            [defauView addSubview:label];
        }
        
        for (int i = 0; i < 2; i ++) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH / 2) * i,  (HEIGHT/3 - 80)/2, WIDTH/2, (HEIGHT / 3 - 80)/2)];
            label.text = keyArr[i + 3];
            label.font = [UIFont systemFontOfSize:14];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor colorWithRed:0.498 green:0.647 blue:0.894 alpha:1.000];
            [defauView addSubview:label];
        }
        
        
        UIView *view2 = (UIView *)[view viewWithTag:201];
        view2.backgroundColor = [UIColor whiteColor];
        NSArray *phoyoArr = detaiObj.photo;
        UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, view2.frame.size.height)];
        myScroll.showsHorizontalScrollIndicator = NO;
        myScroll.contentSize = CGSizeMake((WIDTH/ 2.5)*phoyoArr.count + 20, view2.frame.size.height);
        [view2 addSubview:myScroll];
        for (int i = 0; i < phoyoArr.count; i ++) {
            UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH/2.5 + 5) * i, 0, WIDTH/ 2.5, view2.frame.size.height)];
            [imgview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",phoyoArr[i]]]];
            [myScroll addSubview:imgview];
        }
        
        
        
        UIView *view3 = (UIView *)[view viewWithTag:202];
        view3.backgroundColor = [UIColor whiteColor];
        
        UILabel *detailLabel = [[UILabel alloc] init];
        detailLabel.numberOfLines = 0;
        detailLabel.font = [UIFont systemFontOfSize:12];
        detailLabel.textColor = [UIColor colorWithWhite:0.436 alpha:1.000];
        [view3 addSubview:detailLabel];
        [detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(view3);
            make.size.mas_equalTo(CGSizeMake(view3.frame.size.width - 10, view3.frame.size.height-10));
        }];
         detailLabel.text = [NSString stringWithFormat:@"%@",detaiObj.info];
        
        
        UILabel *comlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 40 + defauView.frame.size.height + 5, 100, 30)];
        comlabel.text = @"评论列表";
        comlabel.font = [UIFont systemFontOfSize:13];
        comlabel.textColor = [UIColor colorWithWhite:0.413 alpha:1.000];
        [view addSubview:comlabel];
        
        UIButton *comBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [comBtn setBackgroundImage:[UIImage imageNamed:@"moviereview_default_18x19_"] forState:UIControlStateNormal];
        [comBtn addTarget:self action:@selector(buttonClick:)  forControlEvents:UIControlEventTouchUpInside];
        comBtn.tag = 777;
        [view addSubview:comBtn];
        [comBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(view.mas_bottom).offset(-10);
            make.right.equalTo(view.mas_right).offset(-10);
            make.size.mas_equalTo(CGSizeMake(18, 19));
        }];
        
        
        
    }
    return view;
}

- (void)buttonClick:(UIButton *)sender
{
    UIView *bgView = (UIView *)[self.view viewWithTag:10086];
    UIButton *button1 = (UIButton *)[bgView viewWithTag:100];
    UIButton *button2 = (UIButton *)[bgView viewWithTag:101];
    UIButton *button3 = (UIButton *)[bgView viewWithTag:102];
    UILabel *label = (UILabel *)[bgView viewWithTag:123456];
    NSArray *arr = @[@"一个 电影表",@"剧照",@"电影信息"];
    if (sender.tag == 100) {
        button1 .selected = YES;
        button2.selected = NO;
        button3.selected = NO;
        UIView *view1 = (UIView *)[bgView viewWithTag:200];
        [bgView bringSubviewToFront:view1];
        label.text = arr[0];
    }else if (sender.tag == 101)
    {
        button2.selected = YES;
        button1.selected = NO;
        button3.selected = NO;
        UIView *view2 = (UIView *)[bgView viewWithTag:201];
        [bgView bringSubviewToFront:view2];
        label.text = arr[1];
    }else if(sender.tag == 102)
    {
        button3.selected = YES;
        button1.selected = NO;
        button2.selected = NO;
        UIView *view3 = (UIView *)[bgView viewWithTag:202];
        [bgView bringSubviewToFront:view3];
        label.text = arr[2];
    }else if (sender.tag == 666)
    {
        UIButton *btn = (UIButton *)[self.view viewWithTag:666];
        btn.selected = !btn.selected;
    //故事点赞
    }else if(sender.tag == 777)
    {
    //评分跳转
        
    }else if (sender.tag ==10000){
    //预告片
        NSLog(@"bgBtn-----%@",detaiObj.video);
        if (!player ) {
            NSMutableString *urlStr = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%@",detaiObj.video]];
            NSLog(@"%@",urlStr);
            playerView = [[PlayerVC alloc] init];
            playerView.view.frame = CGRectMake(0, 64 , WIDTH, HEIGHT/3 - 40);
            playerView.urlStr = urlStr;
            [self.view addSubview:playerView.view];
            

            
        }
    }else if (sender.tag == 3333){
    //买票
        NSDictionary *ticketPara = @{URLKEY : [NSString stringWithFormat:@"movie/buyticket/%@?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0NjM5Mjk2MTgsInVzZXJpZCI6IjY4MDczMDUifQ.F5v0dNsB2b0M8kl91TYtOP1WwdEkZ2DTllnUTbgchkM",self.topicObj.ID]};
        htmlStr = [NSString stringWithFormat:@"%@%@",APISERVICE_URL,ticketPara[URLKEY]];
        NSLog(@"%@",htmlStr);
        ticketVC = [[TicketViewController alloc] init];
        ticketVC.htmlStr = htmlStr;
        [self.navigationController pushViewController:ticketVC animated:YES];
        
    }else if (sender.tag == 3334){
    //评分
        scoreView = [[ScoreVC alloc] init];
        scoreView.view.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
        [self.view addSubview:scoreView.view];
        
    }

}


- (void)BeGanAnimateWithButton:(UIButton *)button
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation.duration = 6;
    animation.repeatCount = MAXFLOAT;
    animation.autoreverses = YES;
    animation.fillMode = kCAFillModeForwards;
    animation.fromValue = [NSNumber numberWithFloat:1.0];
    animation.toValue = [NSNumber numberWithFloat:1.2];
    [button.layer addAnimation:animation forKey:@"scale-layer"];
}

- (void)addNotification
{
//    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//    [center addObserver:self selector:@selector() name:<#(nullable NSString *)#> object:<#(nullable id)#>]
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
